import { login, getTenantList, getMyDept } from "@/api";

const user = {
  namespaced: true,
  state: {
    userName: "", // 用户名
    realName: "", // 用户姓名
    id: "", // 用户id
    sex: "", // 性别
    email: "", // 邮箱
    sysHeadMenuList: [],
    avatar: "", // 头像
    userType: "", // 未知
    mobile: "", // 手机号
    roleList: [],
    permissions: [], // 权限按钮
    tenantList: [], // 租户列表
    tenant: "", // 当前租户
    tenantId: "",
    deptId: "", // 部门ID
    deptName: "", // 部门名称
    platformCode: "SUPERVISE",
  },

  mutations: {
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    },
    // 租户列表赋值
    SET_TANANT: (state, data) => {
      state.tenantList = data;
    },
    // 切换租户
    SET_TENANT: (state, data) => {
      state.tenant = data;
    },
    // 存储部门
    SET_DEPT: (state, { deptName, deptId }) => {
      state.deptId = deptId;
      state.deptName = deptName;
    },
    // 用户信息存储
    SET_USERINFO: (state, data) => {
      console.log("🤡 ~ user.mutations.data:-( ", user.mutations.data);

      function setInfo(data, key, defaultVal = "") {
        if (!data) {
          state[key] = defaultVal;
          return;
        }
        if (!Object.hasOwnProperty.call(data, key)) {
          return;
        }
        state[key] = !data[key] ? defaultVal : data[key];
      }

      const list = [
        "userName",
        "avatar",
        "sex",
        "deptName",
        "mobile",
        "roleName",
        "id",
        "roleList",
        "tenantId",
        "sysHeadMenuList"
      ];
      list.forEach((i) => {
        setInfo(data, i, i === "roleList" ? [] : "");
      });
    },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then(({ result }) => {
            console.log("🤡 ~ result:", result)
            // token过期时间
            const expires_in = result.expires_in
              ? result.expires_in / 3600
              : "";
            // 存储token
            window.$auth.setToken(result.access_token, expires_in);
            // 存储refresh_token
            window.$auth.setRefresh_token(result.refresh_token, expires_in);
            // 存储id
            window.$auth.setId(result.userId);
            // 存储token前缀
            window.$auth.setTokenPrefix(result.token_type);
            commit("app/SET_LOCK", "0", {
              root: true,
            });
            resolve();
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    // 设置头像
    SetUserAvatar({ commit }, avatarUrl) {
      return new Promise((resolve) => {
        if (avatarUrl) {
          commit("SET_AVATAR", avatarUrl);
        }
        resolve();
      });
    },
    // 获取租户
    GetTennat({ commit }) {
      return new Promise((resolve, reject) => {
        getTenantList()
          .then((res) => {
            const tenantList = res.result;
            if (tenantList && tenantList.length) {
              commit("SET_TANANT", tenantList);
              let tenant;
              if (
                ((tenant = tenantList.find((i) => i.currentTenant)), tenant)
              ) {
                commit("SET_TENANT", tenant.id);
              }
            }
            resolve();
          })
          .catch(reject);
      });
    },
    // 获取部门
    GetDept({ commit }) {
      return new Promise((resolve, reject) => {
        getMyDept()
          .then((res) => {
            const { id: deptId, deptName } = res.result;
            commit("SET_DEPT", {
              deptId,
              deptName,
            });
            resolve();
          })
          .catch(reject);
      });
    },
    // 退出系统
    // LogOut({ commit, state }) {
    //   return new Promise((resolve, reject) => {
    //     logout(state.token)
    //       .then(() => {
    //         commit("SET_PERMISSIONS", []);
    //         removeToken();
    //         resolve();
    //       })
    //       .catch((error) => {
    //         reject(error);
    //       });
    //   });
    // },
    // 前端 登出
    FedLogOut({ commit }) {
      commit("SET_USERINFO");
      // 清除token
      window.$auth.removeToken();
      // 清除refresh_token
      window.$auth.removeRefresh_token();
      // 清除id
      window.$auth.removeId();
      // 清除token前缀
      window.$auth.removeTokenPrefix();
      commit("app/SET_LOCK", "0", {
        root: true,
      });
    },
  },
};

export default user;
